package com.kws.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.common.config.constant.MinioCommonBucket;
import com.kws.common.config.util.DateTimeUtil;
import com.kws.common.core.exception.ServiceException;
import com.kws.system.config.MinioAPI;
import com.kws.system.domain.TbExpertCertificate;
import com.kws.system.mapper.ExpertCertificateMapper;
import com.kws.system.service.ExpertCertificateService;
import org.checkerframework.checker.units.qual.C;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <b>ExpertCertificateServiceImpl</b>
 *
 * @description: ExpertCertificateServiceImpl <br>
 * @date: 2024/11/26 10:09 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class ExpertCertificateServiceImpl extends ServiceImpl<ExpertCertificateMapper, TbExpertCertificate> implements ExpertCertificateService {
    private static final Logger logger = LoggerFactory.getLogger(ExpertCertificateServiceImpl.class);

    @Autowired
    private MinioAPI minioAPI;

    private final static String SLASH = "/";

    private final static String FILE_NAME_PREFIX_SEPARATOR = "-";

    @Value("${minio.ENDPOINT}")
    private String minioUrl;

    @Override
    public void saveExpertCertificate(Long id, List<MultipartFile> fileList) {
         List<TbExpertCertificate> expertCertificates = new ArrayList<>();
         if (CollectionUtil.isNotEmpty(fileList)){
             fileList.forEach(item -> {
                 TbExpertCertificate tbExpertCertificate = new TbExpertCertificate();
                 tbExpertCertificate.setExpertId(id);
                 tbExpertCertificate.setCertificateName(item.getOriginalFilename());
                 String fileUrl = uploadFile(item);
                 tbExpertCertificate.setCertificateUrl(fileUrl);
                 expertCertificates.add(tbExpertCertificate);
             });
             this.saveBatch(expertCertificates);
         }

    }

    @Override
    public void updateExpertCertificate(Long id, List<Long> fileIds, List<MultipartFile> fileList) {
        if (CollectionUtil.isNotEmpty(fileIds)){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("expert_id",id);
            queryWrapper.notIn("id",fileIds);
            baseMapper.delete(queryWrapper);
        }else {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("expert_id",id);
            baseMapper.delete(queryWrapper);
        }
        List<TbExpertCertificate> expertCertificates = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(fileList)){
            fileList.forEach(item -> {
                TbExpertCertificate tbExpertCertificate = new TbExpertCertificate();
                tbExpertCertificate.setExpertId(id);
                tbExpertCertificate.setCertificateName(item.getOriginalFilename());
                String fileUrl = uploadFile(item);
                tbExpertCertificate.setCertificateUrl(fileUrl);
                expertCertificates.add(tbExpertCertificate);
            });
            this.saveBatch(expertCertificates);
        }
    }

    public String uploadFile(MultipartFile file) {
        try (InputStream is = file.getInputStream()) {
            String bucketName = MinioCommonBucket.HUATAI_PUB_BUCKET;
            String objectKey = getObjectKey(file.getSize(), file.getOriginalFilename());
            minioAPI.uploadInputStream(bucketName, objectKey, is, file.getContentType());
            logger.info("上传地址为:{}"+objectKey);
            return minioUrl+"/"+MinioCommonBucket.HUATAI_PUB_BUCKET+"/"+objectKey;
        } catch (Exception e) {
            logger.error("上传失败，", e);
            throw new ServiceException("上传失败，请重新上传");
        }
    }

    private String getObjectKey(Long fileSize,String fileName) {
        String date = DateTimeUtil.format(LocalDate.now(),"yyyyMMdd");

        StringBuilder objectKey = new StringBuilder(date);
        objectKey.append(SLASH).append(fileSize).append(FILE_NAME_PREFIX_SEPARATOR).append(fileName);
        return objectKey.toString();
    }
}
